<template>
  <div>
    <el-button @click="beginSign">开始签约</el-button>
    <el-dialog
      title="签约"
      :visible.sync="dialogVisible"
      width="80%"
      top="5vh"
      :before-close="handleClose"
      v-loading="loading"
    >
      <div class="header">
        <div>开始计时：{{ timing }}</div>
      </div>
      <div class="main">
        <!-- 1 -->
        <div class="box">
          <p class="header-title">第一步：开启录像</p>
          <el-button
            style="margin-left: 10px"
            @click="openSign"
            :disabled="!buttonShow"
            >打开摄像头</el-button
          >
          <el-button
            style="margin-left: 10px"
            @click="unPublishVideo"
            :disabled="buttonShow"
            >关闭摄像头</el-button
          >
          <div :class="[notVideoShow == true ? '' : 'notIframe']">
            <video
              id="video"
              :class="[notVideoShow == true ? 'iframe' : 'notIframe']"
            ></video>
          </div>
          <div v-if="!notVideoShow">
            <img
              class="notVideo_img"
              src="../../assets/img/notVideo.png"
              alt=""
            />
            <p class="notYet_p">您还没有打开摄像头~</p>
          </div>
          <!-- :disabled="!notVideoShow" -->
          <el-button class="foot-btn" @click="uplodFu">开始签约</el-button>
        </div>
        <!-- 2 -->
        <div class="box boxToo" v-if="boxShoOne">
          <div class="header">
            <p class="header-title">
              第二步：上传文件(需上传文件个数:{{ templateCount }})
            </p>
            <el-upload
              class="upload-demo"
              :action="action"
              :headers="parmas"
              name="files"
              multiple
              :on-success="handSuccess"
              :on-error="handError"
              :on-progress="handProgress"
              :file-list="fileList"
              :show-file-list="false"
              accept=".PDF,.png"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </div>
          <div class="box-cardHeight">
            <div
              class="box-card"
              v-for="(item, index) in fileImgList"
              :key="index"
            >
              <div class="time">{{ item.createTime }}</div>
              <div class="card_flex">
                <p class="card_url">{{ item.oldName }}</p>
                <p class="card_btn" @click="preview(item.fileUrl)">预览</p>
                <p class="card_btn qx" @click="removeFile(item, 0)">取消</p>
              </div>
            </div>
          </div>
          <p class="title">
            状态：<span style="color: #fb575e">{{ previewState }}</span>
          </p>
          <el-button class="foot-btn" @click="uploadSubmit">提交</el-button>
        </div>
        <div class="box boxToo" v-if="!boxShoOne">
          <div>
            <img class="notYet_img" src="../../assets/img/notYet.png" alt="" />
            <p class="notYet_p">暂无信息展示，请先完成第一步~</p>
          </div>
        </div>
        <!-- 3 -->
        <div class="box" v-if="boxShoToo">
          <div class="header">
            <p class="header-title">第三步：上传合同</p>
            <p class="download" @click="download">下载合同模板</p>
            <el-upload
              class="upload-demo"
              :action="actionTemplate"
              :headers="parmas"
              name="files"
              :on-success="handSuccessHt"
              :on-error="handError"
              :on-progress="handProgress"
              multiple
              :file-list="fileListHt"
              :show-file-list="false"
              accept=".PDF"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </div>
          <div class="box-cardHeight">
            <div
              class="box-card"
              v-for="(item, index) in fileImgListHt"
              :key="index"
            >
              <div class="time">{{ item.createTime }}</div>
              <div class="card_flex">
                <p class="card_url">{{ item.oldName }}</p>
                <p class="card_btn" @click="preview(item.fileUrl)">预览</p>
                <p class="card_btn qx" @click="removeFile(item, 1)">取消</p>
              </div>
            </div>
          </div>
          <p class="title">
            状态：<span style="color: #fb575e">{{ previewStateHt }}</span>
          </p>
          <el-button class="foot-btn" @click="uploadSubmitHt">提交</el-button>
        </div>
        <div class="box" v-if="!boxShoToo">
          <div>
            <img class="notYet_img" src="../../assets/img/notYet.png" alt="" />
            <p class="notYet_p">暂无信息展示，请先完成第二步~</p>
          </div>
        </div>
      </div>
      <el-dialog
        width="45%"
        title="预览文件"
        :visible.sync="innerVisible"
        append-to-body
      >
        <iframe class="previewImg" :src="previewUrl" alt="" />
      </el-dialog>
      <el-dialog
        width="45%"
        title="等待"
        :visible.sync="sginStateble"
        append-to-body
      >
        <span>{{ sginStateText }}</span>
        <span slot="footer" class="dialog-footer">
    <el-button type="primary" @click="sginStateBtn">确 定</el-button>
  </span>
      </el-dialog>
    </el-dialog>
  </div>
</template>
<script>
import {
  getIsAgree,
  getCompleted,
  postObtainRtc,
  deleteFile,
  postDownload,
  getCompletedHt,
  getSginState,
} from "../../../src/assets/js/api";

export default {
  name: "ChannelSign",
  props: ["orderNumber"],

  data() {
    return {
      aliWebrtc: new window.AliRtcEngine(),
      dialogVisible: false,
      innerVisible: false,
      sginStateble: false,
      loading: false,
      fileList: [],
      fileImgList: [],
      fileListHt: [],
      fileImgListHt: [],
      timing: "", // 计时器
      hour: 0, //定义时，分，秒，毫秒并初始化为0；
      minute: 0,
      ms: 0,
      second: 0, //秒
      time: "",
      boxShoOne: false,
      boxShoToo: false,
      notVideoShow: false,
      action: "",
      actionTemplate: "",
      timerAgree: "",
      timerState: "",
      id: "",
      userId: "",
      parmas: {
        CHANNEL_TOKEN: "",
      },
      buttonShow: true,
      previewUrl: "",
      templateCount: "",
      previewState: "上传中",
      previewStateHt: "上传中",
      sginStateText: "提交成功，等待后台确定",
    };
  },
  destroyed() {
    clearTimeout(this.timerAgree);
  },
  created() {
    let token = localStorage.getItem("token");
    this.parmas.CHANNEL_TOKEN = token;
  },
  methods: {
    // // 开始签约
    beginSign() {
      this.getIsAgree();
      this.timerAgree = setInterval(this.getIsAgree, 6000);
    },
    getIsAgree() {
      getIsAgree(this.orderNumber).then((res) => {
        if (res.code == 200 && res.data.agree == true) {
          this.dialogVisible = true;
          this.id = res.data.id;
          this.templateCount = res.data.templateCount;
          this.action = `${this.axios.defaults.baseURL}/channel/contract/sign/finger/${res.data.id}`;
          this.actionTemplate = `${this.axios.defaults.baseURL}/channel/contract/sign/template/${res.data.id}`;
        } else {
          this.dialogVisible = false;
          this.$message.error(res.message);
          clearTimeout(this.timerAgree);
          this.clear();
        }
      });
    },
    // beginSign() {},
    // 上传附件按钮
    uplodFu() {
      this.boxShoOne = true;
      this.time = setInterval(this.timer, 50);
      // this.timerAgree = setInterval(this.getIsAgree, 6000)
    },
    // 获取摄像头数据
    getlistVideo() {},
    // 摄像头
    openSign() {
      postObtainRtc(this.id).then((res) => {
        if (res.code == 200) {
          this.authInfo = res.data;
        }
      });
      this.notVideoShow = true;
      this.aliWebrtc
        .getDevices()
        .then((re) => {
          console.log(re, "0");
        })
        .catch((error) => {
          console.log(error.message + "---getDevices");
        });
      // 当检测有设备时的操作
      this.aliWebrtc
        .isSupport()
        .then((re) => {
          console.log(re);
        })
        .catch((error) => {
          console.log(error.message + "---isSupport");
        });
      this.openVideo();
    },
    // 加入房间
    joinVideo() {
      let userName = "渠道";
      this.aliWebrtc.joinChannel(this.authInfo, userName).then(
        () => {
          // 入会成功
          console.log("入会成功");
          this.publishVideo();
        },
        (error) => {
          // 入会失败，打印错误内容，可以看到失败原因
          console.log(error, "123");
        }
      );
    },
    // 发布本地流
    publishVideo() {
      this.aliWebrtc.publish().then(
        () => {
          console.log("发布本地流成功");
          this.buttonShow = false;
          this.notVideoShow = true;
        },
        (error) => {
          console.log(error, "00");
        }
      );
    },
    // 结束本地流
    unPublishVideo() {
      // 结束本地流
      this.aliWebrtc.unPublish().then(
        () => {
          console.log("结束本地流成功");
          // 退出频道
          this.aliWebrtc.leaveChannel().then(
            () => {
              // 关闭摄像头
              this.stopVideo();
              this.buttonShow = true;
            },
            (error) => {
              console.log(error.message, "p");
            }
          );
        },
        (error) => {
          console.log(error, "99");
        }
      );
    },
    // 打开摄像头
    openVideo() {
      let video = document.getElementById("video");
      console.log(video, "video");
      this.aliWebrtc
        .startPreview(
          video // html中的video元素
        )
        .then(() => {
          console.log("打开");
          this.joinVideo();
        })
        .catch((i) => {
          // 预览失败
          console.log(i, "9999");
        });
    },
    // 关闭摄像头
    stopVideo() {
      this.aliWebrtc
        .stopPreview()
        .then(() => {
          this.notVideoShow = false;
        })
        .catch((error) => {
          // 结束预览失败
          console.log(error, "失败");
        });
    },
    // 上传附件提交
    uploadSubmit() {
      getCompleted(this.id).then((res) => {
        if (res.code == 200) {
          this.previewState = "上传完成";
        }
      });
    },
    // 上传合同提交
    uploadSubmitHt() {
      getCompletedHt(this.id).then((res) => {
        if (res.code == 200) {
          this.sginStateble = true;
          this.previewStateHt = "上传完成";
          this.timerState = setInterval(this.getSginState, 6000);
        }
      });
    },
    // 查询签约状态
    getSginState() {
      getSginState(this.id).then((res) => {
        if (res.code == 200) {
          if (res.data.state == 3) {
            this.sginStateText = "签约完成";
          } else if (res.data.state == 4) {
            this.sginStateText = `签约中止${res.data.remake}`;
          }
        } else {
          clearTimeout(this.timerState);
        }
      });
    },
    // 关闭弹框
    sginStateBtn() {
      this.sginStateble = false;
      this.dialogVisible = false;
      this.clear()
    },
    // 下载文件压缩包
    download() {
      postDownload(this.id).then((res) => {
        if (res.code == 200) {
          this.$message.success(res.message);
          // const blob = new Blob([res.data], { type: "application/zip" });
          // const url = window.URL.createObjectURL(blob);
          const link = document.createElement("a");
          link.href = res.data;
          link.click();
          // URL.revokeObjectURL(url);
          // window.location.href = url;
        } else {
          this.$message.error(res.message);
        }
      });
    },
    // 完成签约
    endSubmit() {
      clearInterval(this.time);
    },
    // 计时器
    timer() {
      //定义计时函数
      this.ms = this.ms + 50; //毫秒
      if (this.ms >= 1000) {
        this.ms = 0;
        this.second = this.second + 1; //秒
      }
      if (this.second >= 60) {
        this.second = 0;
        this.minute = this.minute + 1; //分钟
      }
      if (this.minute >= 60) {
        this.minute = 0;
        this.hour = this.hour + 1; //小时
      }
      this.timing =
        this.toDub(this.hour) +
        ":" +
        this.toDub(this.minute) +
        ":" +
        this.toDub(this.second); /*+""+this.toDubms(this.ms)+"毫秒"*/
      if (this.timing > "00:29:59") {
        clearInterval(this.time);
        this.clear()
      }
    },
    toDub(n) {
      if (n < 10) {
        return "0" + n;
      } else {
        return "" + n;
      }
    },
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then(() => {
          done();
          this.clear();
        })
        .catch(() => {});
    },
    clear() {
      clearInterval(this.time);
      clearTimeout(this.timerState);
      clearTimeout(this.timerAgree);
      this.timing = "";
      this.hour = 0;
      this.minute = 0;
      this.ms = 0;
      this.second = 0;
      this.time = "00:00:00";
      this.stopVideo();
    },
    // 上传中
    handProgress() {
      this.loading = true;
    },
    // 上传成功
    handSuccess(file) {
      this.loading = false;
      this.fileImgList.push(file.data[0]);
      this.templateCount = this.templateCount - 1;
    },
    // 上传失败
    handError() {
      this.loading = false;
      this.$message.error("上传失败");
    },
    // 上传成功
    handSuccessHt(file) {
      this.loading = false;
      this.fileImgListHt.push(file.data[0]);
      this.templateCount = this.templateCount - 1;
    },
    beforeRemove() {},
    // 预览
    preview(item) {
      console.log(item);
      this.previewUrl = item;
      this.innerVisible = true;
    },
    // 删除附件
    removeFile(item, type) {
      this.loading = true;
      deleteFile(item.id).then((res) => {
        this.loading = false;
        if (res.code == 200) {
          this.$message.success(res.message);
          if (type == 0) {
            let index = this.fileImgList.findIndex((i) => {
              if (i.id == item.id) {
                return true;
              }
              return i != item.id;
            });
            this.fileImgList.splice(index, 1);
            this.templateCount = this.templateCount + 1;
          } else {
            let index = this.fileImgListHt.findIndex((i) => {
              if (i.id == item.id) {
                return true;
              }
              return i != item.id;
            });
            this.fileImgListHt.splice(index, 1);
          }
        } else {
          this.$message.error(res.message);
        }
      });
    },
  },
};
</script>
<style scoped type="less">
.main {
  width: 100%;
  height: 600px;
  display: flex;
  justify-content: space-between;
  box-sizing: border-box;
}
.header {
  width: 100%;
  height: 50px;
  display: flex;
  justify-content: space-between;
  box-sizing: border-box;
}
.header div {
  flex: 1;
  line-height: 50px;
}
.box {
  flex: 1;
  padding: 0 10px;
  position: relative;
}
.boxToo {
  border-left: 1px #999999 solid;
  border-right: 1px #999999 solid;
}
.notYet_p {
  font-size: 16px;
  font-family: Microsoft YaHei;
  font-weight: 400;
  color: #343434;
  line-height: 21px;
}
.notYet_img {
  width: 154px;
  height: 154px;
  margin-top: 160px;
}
.notVideo_img {
  width: 143px;
  height: 104px;
  margin-top: 110px;
}
.el-button {
  margin: 20px 0;
}
.iframe {
  width: 100%;
  height: 400px;
}
.notIframe {
  width: 0;
  height: 0;
}
.title {
  margin: 20px 0;
  font-size: 15px;
}
.header-title {
  font-size: 15px;
  font-family: PingFang SC;
  font-weight: bold;
  color: #333333;
  text-align: left;
  height: 30px;
}
.foot-btn {
  position: absolute;
  bottom: 0;
  width: 200px;
  left: 150px;
}
.header {
  display: flex;
}
::v-deep .upload-demo {
  text-align: right;
  margin-top: -20px;
}
.box-cardHeight {
  height: 430px;
  overflow: auto;
}
.box-card {
  padding: 20px;
  margin-bottom: 20px;
  border-radius: 5px;
  background-color: #f8f8f8;
}
.time {
  text-align: left;
  font-size: 12px;
  font-family: PingFang SC;
  color: #999999;
}
.card_flex {
  display: flex;
  margin-top: 10px;
}
.card_url {
  flex: 1;
  font-size: 14px;
  font-family: Microsoft YaHei;
  color: #333333;
  text-align: left;
}
.card_btn {
  text-align: right;
  color: #52aaf8;
  font-size: 12px;
  border: 1px #52aaf8 solid;
  border-radius: 5px;
  padding: 0 5px;
  height: 20px;
  line-height: 20px;
}
.card_btn:hover {
  cursor: pointer;
}
.qx {
  color: #fb575e;
  border: 1px #fb575e solid;
  margin-left: 10px;
}
.download {
  margin-left: 20px;
  font-size: 14px;
  font-family: PingFang SC;
  font-weight: 500;
  text-decoration: underline;
  color: #52aaf8;
}
.download:hover {
  cursor: pointer;
}
.box-cardHeight::-webkit-scrollbar {
  /*滚动条整体样式*/
  width: 10px; /*高宽分别对应横竖滚动条的尺寸*/
  height: 1px;
}
.box-cardHeight::-webkit-scrollbar-thumb {
  /*滚动条里面小方块*/
  border-radius: 5px;
  -webkit-box-shadow: inset 0 0 5px #52aaf8;
  background: #52aaf8;
}
.box-cardHeight::-webkit-scrollbar-track {
  /*滚动条里面轨道*/
  -webkit-box-shadow: inset 0 0 5px #ededed;
  border-radius: 5px;
  background: #ededed;
}
.previewImg {
  width: 100%;
  height: 500px;
}
</style>